import {query} from './tools/db'

function User(id,username,password,nickname,email,status,created) {
   this.id= id;
   this.username= username;
   this.password= password;
   this.nickname= nickname;
   this.email= email;
   this.status= status;
   this.created= created;
}
User.create = (obj) => new User(obj.id, obj.username, obj.password, obj.nickname, obj.email, obj.status, obj.created);



//查询用户名是否存在
User.existUsername = (username) => new Promise(
    (resolve, reject) => {
        query('select count(1) as num from users where username = ?', [username])
        .then(res => {
            resolve(res[0].num > 0)
        })
        .catch(reject)}
);


User.getList=function () {

};

User.getByUsername=(username) =>new Promise(
    (resolve,reject)=> {
        query('select * from users where username = ?', [username])
            .then(res => {
                const row = res[0];
                if (!res[0]) {
                    resolve(null)
                } else {
                    resolve(User.create(res[0]))
                }
            })
            .catch(reject)
    });


User.prototype.save=function () {
    return new Promise(
        (resolve,reject)=>{
        query('insert into users set ?',this)
            .then(result=>{
                this.id =result.insertId;
                if(this.username!=null){
                    resolve(this)
                }else{
                    reject();
                }
            })
            .catch(reject)
         }
    );

};


User.prototype.update=function () {
    return [];
};



export default User;